﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http.Filters;   
using DTCash.Logger.DTO;
using DTCash.Logger;

namespace Uranus.WeiStationAPI
{
    public class ApiExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var message = context.Exception.Message + " " + context.Exception.StackTrace;
            if (context.Exception.InnerException != null) message = message + " " + context.Exception.InnerException.Message;
            string result = "{\"code\":-1,\"data\":\"内部异常\"}";
            string UserID = string.Empty;
            if (context.Request.Properties.ContainsKey("Parameter"))
            {
                Dictionary<string, object> dictionary =
                    context.Request.Properties["Parameter"] as Dictionary<string, object>;
                if (dictionary.ContainsKey("UserID"))
                {
                    UserID = dictionary["UserID"].ToString();
                }
                if (dictionary.ContainsKey("callback"))
                {
                    result = string.Format("{0}({1})", dictionary["callback"], result);
                }

            }
             
            LogHelper.WriteLog(LogEnum.Error, "API异常", message, new { userid = UserID });

            context.Response = new HttpResponseMessage() { Content = new StringContent(result) };
            if (context.Request.Method.Method == "POST")
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }
            base.OnException(context);
        }
    }
}